package com.weex.app.extend;

import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.pm.PackageManager;

import com.taobao.weex.annotation.JSMethod;
import com.taobao.weex.bridge.JSCallback;
import com.taobao.weex.common.WXModule;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class WxUsageStats extends WXModule {

    @JSMethod(uiThread=false)
    public void query(
            final int interval,
            final long begin_time,
            final long end_time,
            JSCallback callback
    ) throws PackageManager.NameNotFoundException {

        Context context = mWXSDKInstance.getContext();
        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(
            interval,
            begin_time,
            end_time
        );

        List<Object[]> li = new ArrayList<Object[]>();
        if (!(queryUsageStats == null || queryUsageStats.isEmpty())) {
            for(UsageStats us:queryUsageStats){
                long cost = us.getTotalTimeInForeground();
                if(cost > 1000){

                    // getFirstTimeStamp
                    // 获取此UsageStats代表的时间范围的开头，以纪元为单位以毫秒为单位。

                    // getLastTimeStamp
                    // 得到这个UsageStats代表的时间范围的结束，以自纪元以​​来的毫秒数来衡量。

                    // getLastTimeUsed
                    // 获取最后一次使用此程序包，自纪元以来以毫秒为单位。

                    Object t[] = {
                        us.getPackageName(),
                        cost/1000,
                        us.getFirstTimeStamp(),
                        us.getLastTimeStamp()
                    };
                    li.add(t);
                }
            }
        }
        Collections.sort(li, new Comparator<Object[]>() {
            public int compare(Object[] a, Object[] b) {
                return Long.compare((long) b[1], (long) a[1]);
            }
        });

        callback.invoke(li);
    }

    @JSMethod(uiThread=false)
    public void ping(JSCallback callback) {

        long ts = System.currentTimeMillis();
        List<UsageStats> queryUsageStats = usageStats().queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, ts);

        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            callback.invoke(false);
        }

        callback.invoke(true);
    }

    private UsageStatsManager usageStats(){
        return (UsageStatsManager) mWXSDKInstance.getContext().getSystemService(Context.USAGE_STATS_SERVICE);
    }

    @JSMethod(uiThread=false)
    public void eventLi(final long beginTime,final long endTime, JSCallback callback) {
        UsageStatsManager usageStatsManager = usageStats();
        UsageEvents usageEvents = usageStatsManager.queryEvents(beginTime, endTime);

        UsageEvents.Event event = new UsageEvents.Event();

        List<Object[]> li = new ArrayList<Object[]>();

        long pre_time = beginTime;
        int eventType=0;
        String pkgName = null;
        String clsName = null;

        while (usageEvents.getNextEvent(event)) {
            eventType = event.getEventType();
            pkgName = event.getPackageName();
            long timestamp = event.getTimeStamp();

            clsName = event.getClassName();
            if(clsName!=null && clsName.startsWith(pkgName+".")){
                clsName=clsName.substring(pkgName.length() + 1);
            }
            switch (eventType){
                case UsageEvents.Event.MOVE_TO_BACKGROUND:
                    Object a[] = {
                            eventType,
                            pre_time,
                            pkgName,
                            clsName,
                            timestamp - pre_time
                    };
                    pre_time=timestamp;
                    li.add(a);
                    break;
                case UsageEvents.Event.MOVE_TO_FOREGROUND:
                    pre_time=timestamp;
                    break;
                default:
                    Object b[] = {
                            eventType,
                            timestamp,
                            pkgName,
                            clsName,
                    };
                    li.add(b);
            }
        }
        if(eventType==UsageEvents.Event.MOVE_TO_FOREGROUND){
            Object c[] = {
                    UsageEvents.Event.MOVE_TO_BACKGROUND,
                    pre_time,
                    pkgName,
                    clsName,
                    endTime - pre_time
            };
            li.add(c);
        }
        callback.invoke(li);
    }

}
